package com.empirisoftware.datastore;

import java.io.Serializable;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import com.empirisoftware.api.HasKey;
import com.empirisoftware.api.ObjectNotFoundException;
import com.google.inject.Inject;

public class DaoImpl implements DAO {
	private final PMF pmf;

	@Inject
	public DaoImpl(PMF pmf) {
		this.pmf = pmf;
	}

	public <T extends HasKey> T save(Class<T> clazz, T o) throws DatastoreException {
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			o = pm.makePersistent(o);
		} catch (RuntimeException e) {
			throw new DatastoreException(e);
		} finally {
			pm.close();
		}
		return o;
	}

	public <T extends Serializable> T get(Class<T> clazz, Serializable key)
			throws ObjectNotFoundException, DatastoreException {
		T retVal = null;
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			retVal = pm.getObjectById(clazz, key);
			return retVal;
		} catch (JDOObjectNotFoundException e) {
			throw new ObjectNotFoundException(clazz, key);
		} catch (RuntimeException e) {
			throw new DatastoreException(e);
		} finally {
			pm.close();
		}
	}
}
